-- 模型加载 cxy 2019/06/25
-- 异步加载 先显示加载
-- 加载完再异步加载高清贴图
require 'Common.SetShowModelBlendBones'

ModelLoader = class("ModelLoader")

function ModelLoader:ctor(id, param, loadDonePlayShow,aniDelay)
    self.id = id
    self.gameObject = GameObject.New("ModelLoader_"..id)
    self.transform = self.gameObject.transform
    self.loadDonePlayShow = loadDonePlayShow==nil and true or loadDonePlayShow
    self.hasLoadModel = false
    self.playAppearSound = param['playAppearSound'] or false

    self.loadCo = coroutine.start(function()
        self:loadAsync()
        if param ~= nil then
            local hideShadow = param['hideShadow']
            local shadowHeight = param['shadowHeight'] or 0
            --阴影修改
            if param['objLayer'] then
                utils.setLayer(self.modelGo.transform,param['objLayer'])
            end
            local planarShadow = self.modelGo.transform:Find('PlanarShadow')
            if planarShadow then
                if hideShadow then
                    planarShadow.gameObject:SetActive(false)
                else
                    local shadowMaterial = planarShadow:GetComponent('SkinnedMeshRenderer').material
                    shadowMaterial:SetFloat('_PlaneHeight', shadowHeight)
                end
            end
        end
        self.hasLoadModel = true
        if self.loadDonePlayShow then 
            coroutine.wait(aniDelay or 0.5)
            if utils.IsAvailableGameObject(self.animator) then
                self.animator:CrossFade(string.format("%s_H_ani_%s", self.id, "show"), 0.1)
            end
            self:LoadAppearSound()
        end
    end)
end

function ModelLoader:destroy()
    self.animator = nil
    coroutine.stop(self.loadCo)
    GameObject.Destroy(self.gameObject)
end

function ModelLoader:setParent(parentTf)
    self.transform:SetParent(parentTf, false)
end
function ModelLoader:setPosition(position)
    self.transform.position = position
end

function ModelLoader:loadAsync()
    local prefabPath = utils.GetModelShowPath(self.id)

    self.modelGo = RESM.InstantiateAssetAsync(prefabPath)
    self.modelGo.transform:SetParent(self.transform, false)
    self.animator = self.modelGo:GetComponent('Animator')
    local lua = AddComponent(self.modelGo, SetShowModelBlendBones)
    lua:OnActive()
end

function ModelLoader:HasLoadModel()
    return self.hasLoadModel
end

function ModelLoader:LoadAppearSound()
    if not self.playAppearSound then return end
    local soundPath = string.format("HeroVoice/%s", self.id)
    local actionSoundPath = string.format("AppearSE/%s", self.id)
    AudioManager.StopCurVoice()
    if RESM.FileExists('Res/Audios/HeroVoice/'..self.id..'.mp3') then
        AudioManager.PlayVoice(soundPath,1)
    end
    if RESM.FileExists('Res/Audios/AppearSE/'..self.id..'.mp3') then
        AudioManager.PlayVoice(actionSoundPath,2)
    end
end
